package com.sdyc.ndmp.cls.dtd;

import com.alibaba.fastjson.JSON;
import com.sdyc.ndmp.cls.model.KeyWordRuleEntity;
import com.sdyc.ndmp.cls.model.MomW;
import com.sdyc.ndmp.cls.model.SonW;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class KeywordCondition implements Serializable {

    private final static long serialVersionUID = 1L;

    protected String json;

    private MomW momW;

    public KeywordCondition(){
    }

    public KeywordCondition(MomW momW) {
        this.momW=momW;
    }

    public KeywordCondition(String KWREjson) {
        this.momW=convertKWRE2MomW(KWREjson);
    }

    public String getJson() {
        return json;
    }

    public void setJson(String momWjson) {
        this.json = momWjson;
        momW = JSON.parseObject(json,MomW.class);
    }

    public MomW getMomW() {
        return momW;
    }

    public void setMomW(MomW momW) {
        this.momW = momW;
    }

    @Override
    public String toString() {
        return  "KeywordCondition -> "+ JSON.toJSONString(momW);
    }

    public MomW convertKWRE2MomW(String KWREjson){
        KeyWordRuleEntity kwre = JSON.parseObject(KWREjson,KeyWordRuleEntity.class);
        MomW momW =new MomW();
        momW.setContains(kwre.getContains());
        momW.setField(kwre.getField());
        Set<String> wordSet=new HashSet<String>();
        for(String word:kwre.getWords()){
            if(StringUtils.isNotEmpty(word)) {
                wordSet.add(word.toLowerCase());
            }
        }
        momW.setWords(wordSet);
        momW.setSons(convertKWRE2SomW(kwre.getSons()));
        return momW;
    }

    private List<SonW> convertKWRE2SomW(List<KeyWordRuleEntity> kwreList){
        List<SonW> sonWlist=new ArrayList<SonW>();
        for(KeyWordRuleEntity kwre:kwreList){
            SonW sonW=new SonW();
            sonW.setContains(kwre.getContains());
            sonW.setVector(kwre.getVector());
            sonW.setLen(kwre.getLen());
            sonW.setField(kwre.getField());
            Set<String> wordSet=new HashSet<String>();
            for(String word:kwre.getWords()){
                if(StringUtils.isNotEmpty(word)) {
                    wordSet.add(word.toLowerCase());
                }
            }
            sonW.setWords(wordSet);
            sonWlist.add(sonW);
        }
        return sonWlist;
    }
}
